package Array;

/**
 * LC704 二分查找，升序整型数组以及目标值，要找到该值并返回下标
 */
public class BinarySearch {
    public static void main(String[] args) {
        //int[] arr={1,2,4,5,6,9,12,90};
        int[] arr={2,5,6,7,9};
        int target=9;
        BinarySearch binarySearch=new BinarySearch();
        System.out.println(binarySearch.binarySearch(arr,target));
    }

    //采用的是[left,right]闭区间，这样right可以赋值成mid-1
    public int binarySearch(int[] nums, int target) {
        if(target<nums[0]||target>nums[nums.length-1]){
            return -1;
        }
        int left=0,right=nums.length-1;
        while(left<=right){
            int mid=(left+right)/2;
            if(nums[mid]==target){
                return mid;
            }
            else if(nums[mid]>target){
                right=mid-1;
            }
            else if(nums[mid]<target){
                left=mid+1;
            }

        }
        return -1;
    }
}
